package com.hghivln.erpwarehouse.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hghivln.erpwarehouse.system.common.lang.DataGridlView;
import com.hghivln.erpwarehouse.system.entity.Dept;
import com.hghivln.erpwarehouse.system.mapper.DeptMapper;
import com.hghivln.erpwarehouse.system.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hghivln.erpwarehouse.system.vo.DeptVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hghivln
 * @since 2021-06-27
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Override
    public DataGridlView queryAllDept(DeptVo deptVo) {
        QueryWrapper<Dept> qw = new QueryWrapper<>();
        qw.orderByAsc("ordernum");
        List<Dept> depts = getBaseMapper().selectList(qw);
        return new DataGridlView((long) depts.size(),depts);
    }

    @Override
    public DataGridlView queryDeptMaxOrderNum() {
        Integer maxOrderNum = getBaseMapper().queryDeptMaxOrderNum();
        return new DataGridlView(maxOrderNum+1);
    }

    /**
     * 根据ID查询当前部门的子部门的个数
     */
    @Override
    public DataGridlView getDeptChildrenCountById(Integer id) {
        Integer count = getBaseMapper().getDeptChildrenCountById(id);
        return new DataGridlView(count);
    }

    @CachePut(cacheNames = "com.hghivln.erpwarehouse.system.service.impl.DeptServiceImpl",key = "#result.id")
    @Override
    public Dept saveDept(DeptVo deptVo) {
        getBaseMapper().insert(deptVo);
        return deptVo;
    }

    @CachePut(cacheNames = "com.hghivln.erpwarehouse.system.service.impl.DeptServiceImpl",key = "#result.id")
    @Override
    public Dept updateDept(DeptVo deptVo) {
        Dept selectById = getBaseMapper().selectById(deptVo.getId());
        BeanUtil.copyProperties(deptVo,selectById, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        getBaseMapper().updateById(selectById);
        return selectById;
    }

    @CacheEvict(cacheNames = "com.hghivln.erpwarehouse.system.service.impl.DeptServiceImpl",key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Cacheable(cacheNames = "com.hghivln.erpwarehouse.system.service.impl.DeptServiceImpl",key = "#id")
    @Override
    public Dept getById(Serializable id) {
        return super.getById(id);
    }
}
